package com.example.netty.bean;

import com.example.netty.enums.MsgTypeEnum;
import com.example.netty.util.DateUtils;


/**
 * @author: lichong
 * @Date: 2020/1/20 11:27
 * @Description: 服务端的响应码
 *      *[4位信息长度][6位消息类型][12位设备码][TIMEyyyyMMDDHHmmss][body]#
 */
public class ResMsg {
    /**
     * 消息体的开始标识
     */
    public static final String MSG_START = "*";
    /**
     * 消息体的结束标识
     */
    public static final String MSG_END = "#";
    /**
     * 消息类型
     */
    private MsgTypeEnum msgType;
    /**
     * 设备码
     */
    private String snNo;
    /**
     * 数据信息，多个信息用英文逗号分隔
     */
    private String data;

    /**
     * 编码后的消息体
     */
    private String msgBody;

    public ResMsg(MsgTypeEnum msgType, String snNo, String data) {
        this.msgType = msgType;
        this.snNo = snNo;
        this.data = data;
        this.msgBody = getMsgStr();
    }

    public String getMsgBody() {
        return msgBody;
    }

    /**
     * 获取数据串
     * @return
     */
    private String getMsgStr() {
        StringBuilder sb = new StringBuilder(200)
                .append(msgType.getMsgType())
                .append(snNo).append("TIME")
                .append(DateUtils.getStringDate("yyyyMMddHHmmss"))
                .append(data);
        int length = sb.length();
        sb.insert(0, String.format("%04d", length));
        sb.insert(0, MSG_START);
        sb.append(MSG_END);
        msgBody = sb.toString();
        return msgBody;
    }
}
